<?php
/**
 * course_detail controller
 * 
 * 
**/

class CourseDetailController extends AppController {
	var $uses = array('CourseDetail');

	/**
	 * List the course details of a course
	 *
	 * @param $id The id of course
	 */
	function index($id) {
		$this->loadModel('Course');
		$courseAlias = $this->Course->alias;
		$options = array();
		$options['fields'] = array(
			$courseAlias . '.title',
			$courseAlias . '.user_id',
			$courseAlias . '.id',
		);
		$options['conditions'] = array(
			$courseAlias . '.id' => $id,
			$courseAlias . '.del_flg' => 0,
		);
		$options['recursive'] = -1;
		$course = $this->Course->find('first', $options);
		if (!$course) {
			$this->cakeError('error404');
		}
		if ($course['Course']['user_id'] != $this->CustomAuth->user('id')) {
			$this->cakeError('error404');
		}

		$options = array();
		$this->loadModel('Area');
		$options['fields'] = array(
			$this->CourseDetail->alias . '.*',
			$this->Area->alias . '.name',
		);
		$options['conditions'] = array(
			$this->CourseDetail->alias . '.course_id' => $id,
			$this->CourseDetail->alias . '.del_flg' => 0,
		);
		$options['recursive'] = 0;
		$options['limit'] = Configure::read('page_limit');
		$this->paginate = $options;
		$details = $this->paginate('CourseDetail');;
		$this->set(array(
			'course' => $course,
			'details' => $details,
		));
	}

	function delete($id) {
		$userId = $this->CustomAuth->user('id');
		$this->CourseDetail->updateDeleteFlgByUserId($id, $userId, 1);
		$this->redirect($this->referer());
	}
	
	/**
	 * action add schedule for course
	 * @purpose : add schedule for course
	 * @param int $courseId course id
	 */
	function add($courseId){
		if(!(isset($courseId))){
			$this->cakeError('error404');
		}
		if(!is_numeric($courseId)){
			$this->cakeError('error404');
		}
		if(!$this->_checkIsAuthorOfCourse($courseId)){
			$this->Session->setFlash(Messages::error_you_isnt_the_author_of_the_course);
			$this->redirect('error');
		}
		$this->loadModel('Area');
		$this->loadModel('Course');
		$areas = $this->Area->find('list');
		$openDate = date('Y-m-d H:i:s');
		$closeDate = date('Y-m-d H:i:s');
		$addressFlg = 1;
		$this->set(array(
			'areas' => $areas,
			'courseId' => $courseId
		));
		if(!empty($this->data)){
			if(isset($this->params['form'])){//combine to date
				$formData = $this->params['form'];
				$inputOpenDate = $formData['year'].'-'.$formData['month'].'-'.$formData['day'].' '.$formData['openHour'].':'.$formData['openMinute'].':00';
				$inputCloseDate = $formData['year'].'-'.$formData['month'].'-'.$formData['day'].' '.$formData['closeHour'].':'.$formData['closeMinute'].':00';
				$openDate = $inputOpenDate;
				$closeDate = $inputCloseDate;
				$this->data['CourseDetail']['opening_date'] = date('Y-m-d H:i:s', strtotime($inputOpenDate));
				$this->data['CourseDetail']['closing_date'] = date('Y-m-d H:i:s', strtotime($inputCloseDate));
				$addressFlg = $this->data['CourseDetail']['address_flg'];
				$this->CourseDetail->set($this->data);
				if($this->CourseDetail->validateCourseDetail()){
					$this->CourseDetail->set('notice', htmlspecialchars($this->data['CourseDetail']['notice']));
					$this->CourseDetail->set('address01', htmlspecialchars($this->data['CourseDetail']['address01']));
					$this->CourseDetail->set('address02', htmlspecialchars($this->data['CourseDetail']['address02']));
					$this->CourseDetail->set('place_name', htmlspecialchars($this->data['CourseDetail']['place_name']));
					$this->CourseDetail->set('course_id', $courseId);
					$this->CourseDetail->set('modified', date('Y-m-d H:i:s'));
					$this->CourseDetail->set('created', date('Y-m-d H:i:s'));
					if($this->CourseDetail->save()){

						//send email
						$this->_sendEmailAddSchedule($courseId, $inputOpenDate);
						$this->Session->setFlash(Messages::successfully);
						$this->Session->setFlash(Messages::please_check_the_course_schedule_at_the_right_of_course_detail_page, 'default', array(), 'schedule');
						$this->redirect(array('controller' => 'course', 'action' => 'view', $courseId));
					}else{
						$this->Session->setFlash(Messages::error);
					}
				}
			}
		}else{
				$course = $this->Course->getCourseInforById($courseId, array('price', 'course_type', 'area'));
				$this->data['CourseDetail']['area'] = $course['Course']['area'];
				$this->data['CourseDetail']['price'] = $course['Course']['price'];
			}
		$this->set(array('openDate' => $openDate, 'closeDate' => $closeDate, 'address_flg' => $addressFlg));
	}
	
	function _sendEmailAddSchedule($courseId, $inputOpenDate) {
		$this->loadModel('TargetOfWatch');
		$this->loadModel('QueueEmail');
		$this->loadModel('Profile');
		$this->loadModel('Course');
		$userId = $this->CustomAuth->user('id');
		$subject = Messages::email_subject_add_schedule;
		$today = strtotime(date('Y-m-d H:i:s'));
		$openDateArr = date_parse($inputOpenDate);
		$courseInfo = $this->Course->getCourseInforById($courseId, array('title'));
		$title = '';
		if(is_array($courseInfo)){
			$title = $courseInfo[$this->Course->alias]['title'];
		}
		$teacherProfile = $this->Profile->find('first', array(
			'conditions' => array(
				$this->Profile->alias.'.user_id' => $userId
			)
		));
		$view = new View($this);
		$watchList = $this->TargetOfWatch->getTargetOfWatchEmailListByTeacherId($userId);
		if(is_array($watchList)){
			foreach ($watchList as $key => $targetOfWatch) {
				$view->set(array(
					'user' => $targetOfWatch ,
					'teacher' => $teacherProfile,
					'openDateArr' => $openDateArr,
					'courseName' => $title,
					'courseId' => $courseId
				));
				
				$content = $view->render('/elements/email/html/add_schedule', '/email/html/default');
				$view->hasRendered = false;
				$mailTo = array($targetOfWatch['User']['email']);
				
				$data = array(
					'subject' => $subject,
					'email_to' => json_encode($mailTo),
					'content' => $content,
					'status' => QueueEmail::EMAIL_STATUS_NOT_YET_SEND,
					'created' => $today,
					'email_type' => QueueEmail::EMAIL_TYPE_COURSE
				);
				try{
					$this->QueueEmail->save($data);
					unset($this->QueueEmail->id);
				}  catch (Exception $ex){

				}
			}
		}
	}
	/**
	 * action edit schedule for course
	 * @purpose edit schedule for course
	 * @param $detailId - course id
	 */
	function edit($detailId){
		$this->loadModel('Area');
		$this->loadModel('EnteredCourse');
		$this->loadModel('Course');
		if(!(isset($detailId))){
			$this->cakeError('error404');
		}
		if(!is_numeric($detailId)){
			$this->cakeError('error404');
		}
		$courseDetail = $this->CourseDetail->find('first', array('conditions' => array('CourseDetail.id' => $detailId), 'recursive' => -1));
		if(!$this->_checkIsAuthorOfCourse($courseDetail['CourseDetail']['course_id'])){
			$this->Session->setFlash(Messages::error_you_isnt_the_author_of_this_course);
			$this->redirect('error');
		}
		if(!empty($this->data)){//not empty -> update
			if(isset($this->params['form'])){//combine to date
				$formData = $this->params['form'];
				$inputOpenDate = $formData['year'].'-'.$formData['month'].'-'.$formData['day'].' '.$formData['openHour'].':'.$formData['openMinute'].':00';
				$inputCloseDate = $formData['year'].'-'.$formData['month'].'-'.$formData['day'].' '.$formData['closeHour'].':'.$formData['closeMinute'].':00';
				
				$this->data['CourseDetail']['opening_date'] = date('Y-m-d H:i:s', strtotime($inputOpenDate));
				$this->data['CourseDetail']['closing_date'] = date('Y-m-d H:i:s', strtotime($inputCloseDate));
				
				$this->CourseDetail->set($this->data);
				$this->CourseDetail->set('id', $courseDetail['CourseDetail']['id']);
				$this->CourseDetail->set('closing_date', date('Y-m-d H:i:s', strtotime($inputCloseDate)));
				$this->CourseDetail->set('opening_date', date('Y-m-d H:i:s', strtotime($inputOpenDate)));
				$this->CourseDetail->set('notice', htmlspecialchars($this->data['CourseDetail']['notice']));
				$this->CourseDetail->set('address01', htmlspecialchars($this->data['CourseDetail']['address01']));
				$this->CourseDetail->set('address02', htmlspecialchars($this->data['CourseDetail']['address02']));
				$this->CourseDetail->set('place_name', htmlspecialchars($this->data['CourseDetail']['place_name']));
				$this->CourseDetail->set('modified', date('Y-m-d H:i:s'));
				unset($this->CourseDetail->data['CourseDetail']['course_id']);
				
				if($this->CourseDetail->validates()){
					if(!strtotime($inputOpenDate)){// because don't check valid day of month at front page ==> check it @^@
						// if use 
						$this->CourseDetail->validationErrors['opening_date'] = Messages::invalid_opening_date;
					}elseif(!strtotime($inputCloseDate)){
						$this->CourseDetail->validationErrors['closing_date'] = Messages::invalid_closing_date;
					}else{
						if(strtotime($inputCloseDate) <= strtotime($inputOpenDate) ){
							$this->CourseDetail->validationErrors['closing_date'] = Messages::invalid_closing_date_can_not_less_than_the_opening_date;
						}else{
							if($this->CourseDetail->save()){
								$course = $this->Course->getCourseInforById($courseDetail['CourseDetail']['course_id'], array('title'));
								$courseData = array(
									'detail_id' => $detailId,
									'openning_date' => date('Y-m-d H:i:s', strtotime($inputOpenDate)),
									'course_name' => is_array($course) ? $course[$this->Course->alias]['title'] : '',
									'course_url' => FULL_BASE_URL. Router::url(array(
										'controller' => 'course',
										'action' => 'view',
										$courseDetail['CourseDetail']['course_id']
									))
								);
								$this->EnteredCourse->insertUsersOfCourseDetailToSendEmail($courseData, 'edit_schedule.ctp');
								$this->loadModel('QueueEmail');
								$this->QueueEmail->deleteOldEmailData();
								$this->Session->setFlash(Messages::successfully);
								$this->redirect(array('controller' => 'course', 'action' => 'view', $courseDetail['CourseDetail']['course_id']));
							}else{
								$this->Session->setFlash(Messages::error);
							}
						}
						
					}
				}
			}
		}else{
			$this->data = $courseDetail;
		}
		$areas = $this->Area->find('list');
		$this->set(array(
			'areas' => $areas,
			'detailId' => $detailId,
			'openDate' => $this->data['CourseDetail']['opening_date'],
			'closeDate' => $this->data['CourseDetail']['closing_date'],
			'address_flg' => $this->data['CourseDetail']['address_flg']));
	}
	
	/**
	 * action error
	 * @purpose : show error page
	 */
	function error(){

	}
	
	function _checkIsAuthorOfCourse($courseId){
		$this->loadModel('Course');
		$userId = $this->CustomAuth->user('id');
		return $this->Course->isOwner($courseId, $userId);		
	}
}